<template>
  <!-- 参考答案页面 -->
  <NavBar title="参考答案" color="#fff" colorText="#333" brg="#f8f8f8">
  <view class="answer-result-container">
   
    <!-- 主要内容区域 -->
    <view class="main-content">
      <!-- 题目内容区域 -->
      <view v-if="searchResultData && searchResultData.voice_user_img" class="answer-section question-section">
        <image
          :src="searchResultData.voice_user_img"
          mode="scaleToFill"
          class="user-upload-image-full"
          @error="onImageError"
          @click="previewImage(searchResultData.voice_user_img)"
        />
      </view>

      <!-- 参考答案标题区域 -->
      <view v-if="searchResultData && searchResultData.qu_data && searchResultData.qu_data.length > 0" class="reference-title-section">
        <text class="reference-title">参考答案</text>
      </view>

      <!-- 循环显示每个答案，每个答案都是独立的answer-section -->
      <view v-if="searchResultData && searchResultData.qu_data && searchResultData.qu_data.length > 0">
        <view
          v-for="(item, index) in searchResultData.qu_data"
          :key="index"
          class="answer-section"
        >
          <!-- 参考答案标题 -->
          <text class="section-title">参考{{ index + 1 }}：{{ item.qu_content || '题目' }}</text>

          <!-- 题目图片 -->
          <view v-if="item.qu_img" class="reference-image">
            <image
              :src="item.qu_img"
              mode="widthFix"
              class="reference-img"
              @error="onImageError"
            />
          </view>

          <!-- 正确答案 -->
          <view v-if="item.qu_answer" class="correct-answer">
            <text class="answer-label">正确答案</text>
            <view class="answer-list">
              <text
                v-for="(option, optionKey) in item.qu_answer"
                :key="optionKey"
                class="answer-text"
              >
                {{ optionKey }}. {{ option }}
              </text>
            </view>
          </view>
        </view>
      </view>

      <!-- 无数据时的占位符 -->
      <view v-else class="answer-section">
        <text class="section-title">参考答案</text>
        <view class="no-data-placeholder">
          <text class="placeholder-text">暂无搜题结果</text>
        </view>
      </view>
    </view>

    <!-- 底部操作按钮 -->
    <view class="bottom-actions">
      <view class="action-item" @click="chooseFromAlbum">
        <image class="action-icon" src="/static/update2.png" mode=""></image>
        <text class="action-text">相册选图</text>
      </view>
      <view class="divider"></view>
      <view class="action-item" @click="takePhoto">
        <image class="action-icon" src="/static/update1.png" mode=""></image>
        <text class="action-text">拍照搜题</text>
      </view>
    </view>

    <!-- 登录弹窗组件 -->
    <LoginModal
      ref="loginModalRef"
      @close="onLoginModalClose"
      @skip="onLoginSkip"
      @login="onLoginSuccess"
    />

  </view>
  </NavBar>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import LoginModal from '@/components/LoginModal/LoginModal.vue'
import { isLoggedIn, getCurrentUser, navigateToLogin } from '../../utils/user.js'
import { isWeixinMiniProgram } from '../../utils/platform.js'

// 响应式数据
const currentTime = ref('')
const searchResultData = ref(null) // 搜题结果数据
const loginModalRef = ref() // 登录弹窗引用

// 页面加载时获取当前时间和参数
onMounted(() => {
  updateTime()
  setInterval(updateTime, 1000)
  console.log('参考答案页面已加载')

  // 获取传递过来的搜题数据
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const options = currentPage.options

  if (options.data) {
    try {
      const decodedData = decodeURIComponent(options.data)
      searchResultData.value = JSON.parse(decodedData)
      console.log('接收到搜题结果数据:', searchResultData.value)
    } catch (error) {
      console.error('解析搜题数据失败:', error)
    }
  }
})

// 更新时间
const updateTime = () => {
  const now = new Date()
  currentTime.value = now.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    hour12: false
  })
}

// 图片加载错误处理
const onImageError = (e) => {
  console.error('图片加载失败:', e)
}

// 预览图片
const previewImage = (imageUrl: string) => {
  uni.previewImage({
    urls: [imageUrl],
    current: imageUrl
  })
}

// 拍照功能
const takePhoto = () => {
  // 检查登录状态
  const loginStatus = isLoggedIn()
  if (!loginStatus) {
    // 判断是否为微信小程序
    if (isWeixinMiniProgram()) {
      // 微信小程序显示登录弹窗
      showLoginModal()
    } else {
      // 其他平台跳转到登录页面
      navigateToLogin('/pages/answer-result/answer-result')
    }
    return
  }

  // 检查拍照次数
  if (!checkPhotoAttempts()) {
    uni.showToast({
      title: '拍照次数不足，请购买后使用',
      icon: 'none',
      duration: 2000
    })
    return
  }

  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['camera'],
    success: (res) => {
      console.log('拍照成功:', res)

      // 跳转到拍照进行中页面并关闭当前页面，传递文件路径参数
      uni.redirectTo({
        url: `/pages/photo-progress/photo-progress?filePath=${encodeURIComponent(res.tempFilePaths[0])}`
      });
    },
    fail: (err) => {
      console.error('拍照失败:', err)
      uni.showToast({
        title: '拍照失败，请重试',
        icon: 'none',
        duration: 2000
      })
    }
  })
}

// 相册选图功能
const chooseFromAlbum = () => {
  // 检查登录状态
  const loginStatus = isLoggedIn()
  if (!loginStatus) {
    // 判断是否为微信小程序
    if (isWeixinMiniProgram()) {
      // 微信小程序显示登录弹窗
      showLoginModal()
    } else {
      // 其他平台跳转到登录页面
      navigateToLogin('/pages/answer-result/answer-result')
    }
    return
  }

  // 检查拍照次数
  if (!checkPhotoAttempts()) {
    uni.showToast({
      title: '拍照次数不足，请购买后使用',
      icon: 'none',
      duration: 2000
    })
    return
  }

  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album'],
    success: (res) => {
      console.log('选择图片成功:', res)

      // 跳转到拍照进行中页面并关闭当前页面，传递文件路径参数
      uni.redirectTo({
        url: `/pages/photo-progress/photo-progress?filePath=${encodeURIComponent(res.tempFilePaths[0])}`
      });
    },
    fail: (err) => {
      console.error('选择图片失败:', err)
      uni.showToast({
        title: '选择图片失败，请重试',
        icon: 'none',
        duration: 2000
      })
    }
  })
}

// 检查拍照次数
const checkPhotoAttempts = () => {
  try {
    // 获取当前用户信息
    const currentUser = getCurrentUser()

    if (!currentUser) {
      console.log('用户信息不存在')
      return false
    }

    // 检查pkg_credit字段是否大于0
    const pkgCredit = currentUser.pkg_credit || 0
    console.log('当前用户拍照次数:', pkgCredit)

    return pkgCredit > 0
  } catch (error) {
    console.error('检查拍照次数失败:', error)
    return false
  }
}

// 显示登录弹窗
const showLoginModal = () => {
  loginModalRef.value.open()
}

// 登录弹窗事件处理
const onLoginModalClose = () => {
  console.log('登录弹窗关闭')
}

const onLoginSkip = () => {
  uni.showToast({
    title: '暂不登录',
    icon: 'none',
    duration: 2000
  })
}

const onLoginSuccess = () => {
  // 弹框处理了登录逻辑 这里只处理登录完成逻辑
  console.log('登录成功')
}

// 返回上一页
const goBack = () => {
  uni.navigateBack({
    success: () => {
      console.log('返回成功')
    },
    fail: (err) => {
      console.error('返回失败:', err)
      // 如果返回失败，跳转到首页
      uni.switchTab({
        url: '/pages/index/index'
      })
    }
  })
}
</script>

<style scoped>
.answer-result-container {
  min-height: 100vh;
  background: linear-gradient(180deg, #C2DDFF 0%, #FFFFFF 100%);
  padding-top: 160rpx;
}

/* 状态栏 */
.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 40rpx 10rpx;
  background: transparent;
  position: sticky;
  top: 0;
  z-index: 100;
}

.status-left {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.status-time {
  font-size: 34rpx;
  font-weight: 600;
  color: #1A1A1A;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.back-arrow {
  font-size: 40rpx;
  color: #333;
  font-weight: bold;
}

.status-center {
  flex: 1;
  text-align: center;
}

.page-title {
  font-size: 36rpx;
  font-weight: 700;
  color: #1A1A1A;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.status-right {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.status-icons {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.status-icon {
  font-size: 24rpx;
  color: #1A1A1A;
  opacity: 0.8;
}

/* 主要内容区域 */
.main-content {
  margin: 30rpx;
  display: flex;
  flex-direction: column;
  gap: 30rpx;
}

/* 答案区域 */
.answer-section {
  background: white;
  border-radius: 24rpx;
  padding: 40rpx 40rpx 150rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 30rpx;
  display: block;
}

/* 答案卡片 */
.answer-card {
  background: #f8f9fa;
  border-radius: 16rpx;
  padding: 40rpx;
  min-height: 200rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.question-placeholder {
  text-align: center;
}

.placeholder-text {
  font-size: 28rpx;
  color: #666;
}

/* 参考答案标题区域 */
.reference-title-section {
  margin: 0rpx 15rpx; /* 间隙再减小一半 */
  padding: 5rpx 0; /* 内边距再减小一半 */
  text-align: left; /* 居左显示 */
}

.reference-title {
  font-size: 28rpx; /* 字体调整为28rpx */
  font-weight: 600;
  color: #333;
}

/* 题目图片section */
.question-section {
  padding: 0; /* 移除内边距，让图片完全填充 */
  overflow: hidden;
  height: 400rpx; /* 设置固定高度 */
  min-height: 400rpx;
}

.user-upload-image-full {
  width: 100%;
  height: 100%;
  border-radius: 24rpx; /* 保持与answer-section相同的圆角 */
  cursor: pointer;
  display: block;
}

/* 题目内容 */
.question-content {
  margin-bottom: 20rpx;
  padding: 20rpx;
  background: #fff;
  border-radius: 12rpx;
  border-left: 4rpx solid #007AFF;
}

.question-text {
  font-size: 28rpx;
  color: #333;
  line-height: 1.6;
  font-weight: 600;
}

/* 选项列表 */
.answer-options {
  margin-bottom: 20rpx;
}

.option-item {
  padding: 12rpx 20rpx;
  margin-bottom: 8rpx;
  background: #f8f9fa;
  border-radius: 8rpx;
  border: 1rpx solid #e9ecef;
}

.option-text {
  font-size: 26rpx;
  color: #495057;
  line-height: 1.5;
}

/* 参考图片 */
.reference-img {
  max-width: 100%;
  border-radius: 8rpx;
}

/* 答案列表 */
.answer-list {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

/* 无数据占位符 */
.no-data-placeholder {
  text-align: center;
  padding: 60rpx 20rpx;
  background: #f8f9fa;
  border-radius: 16rpx;
}

/* 参考项目 */
.reference-item {
  margin-bottom: 40rpx;
  padding: 30rpx;
  background: #f8f9fa;
  border-radius: 16rpx;
}

.reference-item:last-child {
  margin-bottom: 0;
}

.reference-header {
  margin-bottom: 20rpx;
}

.reference-label {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
}

.reference-content {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

/* 功能列表 */
.feature-list {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.feature-item {
  font-size: 24rpx;
  color: #666;
  line-height: 1.5;
}

/* 参考图片 */
.reference-image {
  background: #e0e0e0;
  border-radius: 12rpx;
  padding: 40rpx;
  text-align: center;
  min-height: 120rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.image-placeholder {
  font-size: 24rpx;
  color: #999;
}

/* 正确答案 */
.correct-answer {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.answer-label {
  font-size: 26rpx;
  font-weight: 600;
  color: #333;
}

.answer-text {
  font-size: 28rpx;
  font-weight: 700;
  color: #ff4444;
}

/* 底部操作按钮 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx 0;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.action-item {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx;
  gap: 8rpx;
  transition: all 0.3s ease;
}

.action-icon {
  width: 65rpx;
  height: 65rpx;
  margin-right: 15rpx;
}

.action-text {
  font-size: 28rpx;
  color: #333;
  font-weight: 600;
}

.divider {
  width: 2rpx;
  height: 60rpx;
  background: #e0e0e0;
}

/* 底部指示条 */
.bottom-indicator {
  position: fixed;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 120rpx;
  height: 8rpx;
  background: #000;
  border-radius: 4rpx;
  margin-bottom: 10rpx;
}
</style>
